// Protocol3 系统核心类型定义
// 提供完整的类型安全支持和工具函数

// ==================== 基础枚举类型 ====================

/**
 * Protocol3 协议类型枚举
 * 支持三种协议类型：商户渠道配置协议、二维码配置协议和默认协议
 */
export enum ProtocolType3 {
  MERCHANT_CHANNEL_CONFIG_V3 = 'MERCHANT_CHANNEL_CONFIG_V3',
  QR_CODE_CONFIG = 'QR_CODE_CONFIG',
  DEFAULT_PROTOCOL = 'DEFAULT_PROTOCOL'
}

/**
 * 字段类型枚举
 */
export enum FieldType {
  INPUT = 'INPUT',
  PASSWORD = 'PASSWORD',
  TEXTAREA = 'TEXTAREA',
  SELECT = 'SELECT',
  RADIO = 'RADIO',
  CHECKBOX = 'CHECKBOX',
  SWITCH = 'SWITCH',
  UPLOAD = 'UPLOAD',
  URL = 'URL',
  EMAIL = 'EMAIL',
  NUMBER = 'NUMBER',
  DATE = 'DATE',
  TIME = 'TIME',
  DATETIME = 'DATETIME',
  COLOR = 'COLOR',
  JSON = 'JSON'
}

/**
 * 协议绑定状态枚举
 */
export enum ProtocolBindingStatus {
  ACTIVE = 'ACTIVE',
  INACTIVE = 'INACTIVE',
  PENDING = 'PENDING'
}

// ==================== 基础接口定义 ====================

/**
 * 字段验证规则
 */
export interface FieldValidation {
  required?: boolean
  pattern?: string
  minLength?: number
  maxLength?: number
  min?: number
  max?: number
  message?: string
}

/**
 * 配置字段定义
 */
export interface ConfigField {
  fieldKey: string
  fieldName: string
  fieldType: FieldType
  required: boolean
  defaultValue: any
  placeholder?: string
  description?: string
  validation?: FieldValidation
  options?: Array<{ label: string; value: any }>
}

/**
 * 配置段定义
 */
export interface ConfigSection {
  sectionKey: string
  sectionName: string
  description?: string
  icon?: string
  order: number
  collapsed?: boolean
  fields: ConfigField[]
}

/**
 * 协议配置工具函数
 */
export const ProtocolConfigUtils = {
  /**
   * 从配置段的字段中生成默认值对象
   */
  getDefaultValues(section: ConfigSection): Record<string, any> {
    const defaults: Record<string, any> = {};
    section.fields.forEach(field => {
      defaults[field.fieldKey] = field.defaultValue || '';
    });
    return defaults;
  },

  /**
   * 从整个协议的所有配置段中生成默认值对象
   */
  getAllDefaultValues(configSections: ConfigSection[]): Record<string, any> {
    const allDefaults: Record<string, any> = {};
    configSections.forEach(section => {
      const sectionDefaults = this.getDefaultValues(section);
      Object.assign(allDefaults, sectionDefaults);
    });
    return allDefaults;
  }
};

/**
 * UI配置
 */
export interface UiConfig {
  layout: 'horizontal' | 'vertical'
  labelWidth?: number
  showDescription?: boolean
  grouping?: 'sections' | 'tabs'
}

/**
 * 元数据信息
 */
export interface Metadata {
  author: string
  createTime: string
  updateTime: string
  tags?: string[]
  category?: string
  documentation?: string
}

// ==================== 核心协议接口 ====================

/**
 * 商户渠道配置协议 V3
 */
export interface MerchantChannelConfig3 {
  protocolId: string
  protocolType: ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3
  channelCode?: string
  channelName?: string
  name: string
  version: string
  description: string
  enabled: boolean
  configType?: string

  // 配置段
  configSections: ConfigSection[]

  // UI配置
  uiConfig: UiConfig

  // 元数据
  metadata: Metadata
}

/**
 * 二维码配置协议
 */
export interface QRCodeConfig {
  protocolId: string
  protocolType: ProtocolType3.QR_CODE_CONFIG
  channelCode?: string
  name: string
  version: string
  description: string
  enabled: boolean

  // 二维码配置
  codeType: 'STATIC' | 'DYNAMIC'
  expireTime?: number
  maxUseCount?: number

  // 配置段
  configSections: ConfigSection[]

  // UI配置
  uiConfig: UiConfig

  // 元数据
  metadata: Metadata
}

/**
 * 默认协议（兜底协议）
 */
export interface DefaultProtocol {
  protocolId: string
  protocolType: ProtocolType3.DEFAULT_PROTOCOL
  channelCode?: string
  name: string
  version: string
  description: string
  enabled: boolean

  // 默认配置
  fallbackConfig: Record<string, any>
  priority: number // 优先级，数字越小优先级越高

  // 配置段
  configSections: ConfigSection[]

  // UI配置
  uiConfig: UiConfig

  // 元数据
  metadata: Metadata
}

// ==================== 协议绑定相关类型 ====================

/**
 * 协议绑定配置
 */
export interface ProtocolBinding {
  bindingId: string
  protocolId: string
  channelCode: string
  channelName: string
  configType: string // 支付渠道的配置类型
  status: ProtocolBindingStatus
  priority: number // 优先级，数字越小优先级越高
  createTime: string
  updateTime: string
  description?: string
}

/**
 * 渠道配置类型
 */
export interface ChannelConfigType {
  configType: string
  configName: string
  channelCode: string
  channelName: string
  description?: string
  enabled: boolean
}

// ==================== 验证和结果类型 ====================

/**
 * 验证结果
 */
export interface ValidationResult {
  valid: boolean
  errors: string[]
  warnings?: string[]
}

/**
 * 字段验证结果
 */
export interface FieldValidationResult {
  valid: boolean
  error?: string
}

/**
 * 测试结果
 */
export interface TestResult {
  success: boolean
  duration: number
  errors: string[]
  warnings: string[]
  details?: any
  protocolId?: string
  timestamp?: string
}

/**
 * 协议解析结果
 */
export interface Protocol3ResolveResult {
  protocol: MerchantChannelConfig3
  protocolId: string
  bindings: ProtocolBinding[]
  isDefault: boolean
  source: 'registry' | 'binding'
  cacheHit: boolean
  resolveTime: number
}

// ==================== 性能和监控类型 ====================

/**
 * 性能指标
 */
export interface PerformanceMetrics {
  resolveCount: number
  averageResolveTime: number
  cacheHitRate: number
  errorRate: number
  totalErrors: number
  uptime: number
}

/**
 * 基准测试结果
 */
export interface BenchmarkResult {
  success: boolean
  errors: string[]
  warnings: string[]
  duration: number
}

/**
 * Mock数据配置
 */
export interface MockDataConfig {
  channels: string[]
  configTypes: string[]
  count?: number
}

/**
 * 缓存统计
 */
export interface CacheStats {
  size: number
  hitRate: number
  missRate: number
  keys: string[]
  totalHits: number
  totalMisses: number
}

/**
 * 日志条目
 */
export interface LogEntry {
  timestamp: string
  level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'
  operation: string
  protocolId?: string
  message: string
  details?: any
  duration?: number
}

/**
 * 健康检查状态
 */
export interface HealthCheck {
  name: string
  status: 'pass' | 'warn' | 'fail'
  message: string
  details?: any
}

/**
 * 系统健康状态
 */
export interface HealthStatus {
  status: 'healthy' | 'degraded' | 'unhealthy'
  checks: HealthCheck[]
  timestamp: string
}

// ==================== 工具函数 ====================

/**
 * 生成协议ID
 */
export function generateProtocolId(prefix: string = 'PROTOCOL3'): string {
  return `${prefix}_${Date.now()}`
}

/**
 * 格式化时间戳
 */
export function formatTimestamp(timestamp: number): string {
  return new Date(timestamp).toISOString()
}

/**
 * 深度克隆对象
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') {
    return obj
  }

  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any
  }

  if (obj instanceof Array) {
    return obj.map(item => deepClone(item)) as any
  }

  if (typeof obj === 'object') {
    const cloned = {} as any
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        cloned[key] = deepClone(obj[key])
      }
    }
    return cloned
  }

  return obj
}

/**
 * 验证字段值
 */
export function validateFieldValue(field: ConfigField, value: any): FieldValidationResult {
  const { validation } = field

  if (!validation) {
    return { valid: true }
  }

  // 必填验证
  if (validation.required && (value === null || value === undefined || value === '')) {
    return {
      valid: false,
      error: validation.message || `${field.fieldName}不能为空`
    }
  }

  // 如果值为空且非必填，则通过验证
  if (!validation.required && (value === null || value === undefined || value === '')) {
    return { valid: true }
  }

  // 字符串长度验证
  if (typeof value === 'string') {
    if (validation.minLength && value.length < validation.minLength) {
      return {
        valid: false,
        error: validation.message || `${field.fieldName}长度不能少于${validation.minLength}个字符`
      }
    }

    if (validation.maxLength && value.length > validation.maxLength) {
      return {
        valid: false,
        error: validation.message || `${field.fieldName}长度不能超过${validation.maxLength}个字符`
      }
    }
  }

  // 数值范围验证
  if (typeof value === 'number') {
    if (validation.min !== undefined && value < validation.min) {
      return {
        valid: false,
        error: validation.message || `${field.fieldName}不能小于${validation.min}`
      }
    }

    if (validation.max !== undefined && value > validation.max) {
      return {
        valid: false,
        error: validation.message || `${field.fieldName}不能大于${validation.max}`
      }
    }
  }

  // 正则表达式验证
  if (validation.pattern && typeof value === 'string') {
    const regex = new RegExp(validation.pattern)
    if (!regex.test(value)) {
      return {
        valid: false,
        error: validation.message || `${field.fieldName}格式不正确`
      }
    }
  }

  return { valid: true }
}

/**
 * 合并验证结果
 */
export function mergeValidationResults(results: ValidationResult[]): ValidationResult {
  const errors: string[] = []
  const warnings: string[] = []

  for (const result of results) {
    if (!result.valid) {
      errors.push(...result.errors)
    }
    if (result.warnings) {
      warnings.push(...result.warnings)
    }
  }

  return {
    valid: errors.length === 0,
    errors,
    warnings
  }
}

/**
 * 生成唯一ID
 */
export function generateUniqueId(prefix: string = 'id'): string {
  return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

/**
 * 检查对象是否为空
 */
export function isEmpty(obj: any): boolean {
  if (obj === null || obj === undefined) {
    return true
  }

  if (typeof obj === 'string' || Array.isArray(obj)) {
    return obj.length === 0
  }

  if (typeof obj === 'object') {
    return Object.keys(obj).length === 0
  }

  return false
}

/**
 * 安全的JSON解析
 */
export function safeJsonParse<T>(jsonString: string, defaultValue: T): T {
  try {
    return JSON.parse(jsonString)
  } catch (error) {
    console.warn('JSON解析失败:', error)
    return defaultValue
  }
}

/**
 * 安全的JSON字符串化
 */
export function safeJsonStringify(obj: any, space?: number): string {
  try {
    return JSON.stringify(obj, null, space)
  } catch (error) {
    console.warn('JSON字符串化失败:', error)
    return '{}'
  }
}

// ==================== 类型守卫函数 ====================

/**
 * 检查是否为MerchantChannelConfig3类型
 */
export function isMerchantChannelConfig3(obj: any): obj is MerchantChannelConfig3 {
  return obj &&
         typeof obj === 'object' &&
         obj.protocolType === ProtocolType3.MERCHANT_CHANNEL_CONFIG_V3 &&
         typeof obj.protocolId === 'string'
}

/**
 * 检查是否为QRCodeConfig类型
 */
export function isQRCodeConfig(obj: any): obj is QRCodeConfig {
  return obj &&
         typeof obj === 'object' &&
         obj.protocolType === ProtocolType3.QR_CODE_CONFIG &&
         typeof obj.protocolId === 'string'
}

/**
 * 检查是否为DefaultProtocol类型
 */
export function isDefaultProtocol(obj: any): obj is DefaultProtocol {
  return obj &&
         typeof obj === 'object' &&
         obj.protocolType === ProtocolType3.DEFAULT_PROTOCOL &&
         typeof obj.protocolId === 'string'
}

/**
 * 检查是否为有效的字段类型
 */
export function isValidFieldType(type: any): type is FieldType {
  return Object.values(FieldType).includes(type)
}

/**
 * 检查是否为有效的协议绑定状态
 */
export function isValidProtocolBindingStatus(status: any): status is ProtocolBindingStatus {
  return Object.values(ProtocolBindingStatus).includes(status)
}

// ==================== 默认值常量 ====================

/**
 * 默认UI配置
 */
export const DEFAULT_UI_CONFIG: UiConfig = {
  layout: 'horizontal',
  labelWidth: 120,
  showDescription: true,
  grouping: 'sections'
}

/**
 * 默认元数据
 */
export const DEFAULT_METADATA: Metadata = {
  author: 'AnyPay Team',
  createTime: new Date().toISOString(),
  updateTime: new Date().toISOString(),
  tags: [],
  category: '默认分类'
}

/**
 * 支持的渠道代码列表
 */
export const SUPPORTED_CHANNELS = [
  'WXPAY',
  'ALIPAY',
  'UNIONPAY',
  'BANK_CARD',
  'DIGITAL_CURRENCY'
] as const

/**
 * 字段类型显示名称映射
 */
export const FIELD_TYPE_NAMES: Record<FieldType, string> = {
  [FieldType.INPUT]: '文本输入',
  [FieldType.PASSWORD]: '密码输入',
  [FieldType.TEXTAREA]: '多行文本',
  [FieldType.SELECT]: '下拉选择',
  [FieldType.RADIO]: '单选按钮',
  [FieldType.CHECKBOX]: '复选框',
  [FieldType.SWITCH]: '开关',
  [FieldType.UPLOAD]: '文件上传',
  [FieldType.URL]: 'URL地址',
  [FieldType.EMAIL]: '邮箱地址',
  [FieldType.NUMBER]: '数字输入',
  [FieldType.DATE]: '日期选择',
  [FieldType.TIME]: '时间选择',
  [FieldType.DATETIME]: '日期时间',
  [FieldType.COLOR]: '颜色选择',
  [FieldType.JSON]: 'JSON格式'
}

/**
 * 协议绑定状态显示名称映射
 */
export const PROTOCOL_BINDING_STATUS_NAMES: Record<ProtocolBindingStatus, string> = {
  [ProtocolBindingStatus.ACTIVE]: '激活',
  [ProtocolBindingStatus.INACTIVE]: '停用',
  [ProtocolBindingStatus.PENDING]: '待激活'
}